package com.nopay.dxdwphone.utils;

import android.app.Activity;
import android.os.Handler;

import com.nopay.dxdwphone.dialog.DialogLoading;

import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.bean.request.SaveCallDataRequest;
import com.nopay.dxdwphone.bean.response.SaveCallDataResponse;
import com.nopay.dxdwphone.db.CallLogBean;
import com.nopay.dxdwphone.net.AssetsRetrofit;
import com.nopay.dxdwphone.net.HttpApi;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 通话记录保存工具
 * author：jun
 * date：2021/8/6
 */
public class CallLogSaveTools {

    private static volatile CallLogSaveTools INSTANCE;

    private final HttpApi mApi = AssetsRetrofit.getInstance().getRetrofit().create(HttpApi.class);
    private final Map<String, CallLogBean> mCallLogMap = new LinkedHashMap<>();

    private CallLogSaveTools() {
        super();
    }

    public static CallLogSaveTools getInstance() {
        if(INSTANCE == null) {
            synchronized (CallLogSaveTools.class) {
                if(INSTANCE == null) {
                    INSTANCE = new CallLogSaveTools();
                }
            }
        }
        return INSTANCE;
    }

    public void save(String phone, CallLogBean bean) {
        bean.save();
        mCallLogMap.put(phone, bean);
    }

    public void update(String phone, String callDate, int duration) {
        CallLogBean bean = mCallLogMap.get(phone);
        if(bean != null) {
            bean.setCallDate(callDate);
            bean.setDuration(duration);
            bean.setStatus(duration > 0 ? 1 : 2);
            bean.save();
            mCallLogMap.put(phone, bean);
        }
    }

    public void delete(String phone) {
        CallLogBean bean = mCallLogMap.get(phone);
        if(bean != null) bean.delete();
        mCallLogMap.remove(phone);
    }

    private DialogLoading mLoading;

    public void hasDataAndSubmitDelayed(final Activity activity, final OnSubmitCompleteListener listener) {
        if(mCallLogMap.size() == 0) {
            if(listener != null) listener.onComplete();
            return;
        }

        if(mLoading == null) {
            mLoading = new DialogLoading(activity);
            mLoading.show("正在保存通话记录...");
        }

        new Handler().postDelayed(() -> {
            // 延迟操作
            hasDataAndSubmit(activity, listener);
        }, 1500);
    }

    public void hasDataAndSubmit(final Activity activity, final OnSubmitCompleteListener listener) {
        if(mCallLogMap.size() == 0) {
            if(mLoading != null) mLoading.dismiss();
            if(listener != null) listener.onComplete();
            return;
        }

        if(mLoading == null) {
            mLoading = new DialogLoading(activity);
            mLoading.show("正在保存通话记录...");
        }

        Iterator<Map.Entry<String, CallLogBean>> iterator = mCallLogMap.entrySet().iterator();
        if(iterator.hasNext()) {
            Map.Entry<String, CallLogBean> dataEntry = iterator.next();
            CallLogBean callLogBean = dataEntry.getValue();

            SaveCallDataRequest bean = new SaveCallDataRequest();
            bean.setCallDate(callLogBean.getCallDate());
            bean.setCalledNumber(callLogBean.getCalledNumber());
            bean.setCallingNumber(callLogBean.getCallingNumber());
            bean.setCompany(callLogBean.getCompany());
            bean.setDuration(callLogBean.getDuration());
            bean.setName(callLogBean.getName());
            bean.setPhone(callLogBean.getPhone());
            bean.setStatus(callLogBean.getStatus());
            bean.setTaskId(callLogBean.getTaskId());

            RequestBody body = getRequestBody(bean);
            mApi.doSaveCallData(body).enqueue(new Callback<SaveCallDataResponse>() {
                @Override
                public void onResponse(@NotNull Call<SaveCallDataResponse> call, @NotNull Response<SaveCallDataResponse> response) {
                    if (response.body() != null) {
                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
                            CallLogSaveTools.getInstance().delete(callLogBean.getCalledNumber());
                        }
                    }
                    mCallLogMap.remove(callLogBean.getCalledNumber());
                    hasDataAndSubmit(activity, listener);
                }

                @Override
                public void onFailure(@NotNull Call<SaveCallDataResponse> call, @NotNull Throwable t) {
                    mCallLogMap.remove(callLogBean.getCalledNumber());
                    hasDataAndSubmit(activity, listener);
                }
            });
        } else {
            if(mLoading != null) mLoading.dismiss();
            if(listener != null) listener.onComplete();
        }
    }

    protected RequestBody getRequestBody(Object object) {
        String jsonStr = GsonUtils.toJson(object);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr);
    }

    public static class Builder {

        private final CallLogBean mBean;

        public Builder() {
            mBean = new CallLogBean();
        }

        public Builder setCallDate(String callDate) {
            if(mBean != null) mBean.setCallDate(callDate);
            return this;
        }

        public Builder setCalledNumber(String calledNumber) {
            if(mBean != null) mBean.setCalledNumber(calledNumber);
            return this;
        }

        public Builder setCallingNumber(String callingNumber) {
            if(mBean != null) mBean.setCallingNumber(callingNumber);
            return this;
        }

        public Builder setCompany(String company) {
            if(mBean != null) mBean.setCompany(company);
            return this;
        }

        public Builder setDuration(int duration) {
            if(mBean != null) mBean.setDuration(duration);
            return this;
        }

        public Builder setName(String name) {
            if(mBean != null) mBean.setName(name);
            return this;
        }

        public Builder setPhone(String phone) {
            if(mBean != null) mBean.setPhone(phone);
            return this;
        }

        public Builder setStatus(int status) {
            if(mBean != null) mBean.setStatus(status);
            return this;
        }

        public Builder setTaskId(Integer taskId) {
            if(mBean != null) mBean.setTaskId(taskId);
            return this;
        }

        public CallLogBean build() {
            return mBean;
        }
    }

    public interface OnSubmitCompleteListener {

        void onComplete();
    }
}
